﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace Passwords.Models
{
    public class ObservableChildCollection<T> : ObservableCollection<T> where T : Entity
    {
        public Entity Parent { get; private set; }

        public bool QuietMode { get; set; }

        public ObservableChildCollection(Entity parent)
            : base()
        {
            if (parent == null) throw new ArgumentNullException("parent");
            this.Parent = parent;
        }

        public ObservableChildCollection(Entity parent, IEnumerable<T> collection)
            : base(collection)
        {
           // if (parent == null) throw new ArgumentNullException("parent");
            this.Parent = parent;
            foreach (T item in collection) item.Parent = parent;
        }

        protected override void ClearItems()
        {
            base.ClearItems();
            NotifyParent();
        }

        protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            base.OnCollectionChanged(e);
            NotifyParent();
        }

        protected override void InsertItem(int index, T item)
        {
            item.Parent = Parent;
            base.InsertItem(index, item);
        }

        protected override void RemoveItem(int index)
        {
            this[index].Parent = null;
            base.RemoveItem(index);
        }

        private void NotifyParent()
        {
            if (QuietMode) return;
            Entity p = Parent;
            if (p != null)
            {
                p.IsModified = true;
                p.OnPropertyChanged("IsModified");
            }
        }
    }
}
